package middle;

public class Solution_395 {

    public static void main(String[] args) {
        Solution_395 model = new Solution_395();
        System.out.println(model.longestSubstring("aaabb", 3));
        System.out.println(model.longestSubstring("ababbc", 2));
        System.out.println(model.longestSubstring("a", 1));
    }

    public int longestSubstring(String s, int k) {
        char[] chars = s.toCharArray();
        int[][] arrays= new int[chars.length][26];
        for (int i = 0; i < chars.length; i++) {
            for (int j = 0; j < 26; j++) {
                if (i > 0) {
                    arrays[i][j] = arrays[i - 1][j];
                }
            }
            arrays[i][chars[i] - 'a']++;
        }
        int max = 0;
        for (int i = 0; i < chars.length && i + max < chars.length; i++) {
            for (int j = chars.length - 1; j >= i + k - 1; j--) {
                boolean flag = true;
                for (int m = 0; m < 26; m++) {
                    int count = arrays[j][m] - (i > 0 ? arrays[i - 1][m] : 0);
                    if (count > 0 && count < k) {
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    max = Math.max(max, j - i + 1);
                    break;
                }
            }
        }
        return max;
    }
}
